<?php
/**
 **2015-10-13
 **门票分销API接口（去哪儿）
 **User by pzp
 **Time 11:00
 **/

class Qunar2B{

    private $partnerCode = '2830068584';
    private $partnerKey = 'slx_key';
    private $Qurl = 'b2bdev.piao.qunar.com';

    public function productInfoList($currentPage){
        $method = '/openapi/productInfoList';

        $request_arr = array(
            'version'		=> '1.1.0',
            'partnerCode'	=> $this->partnerCode,
            'pageNo'		=> $currentPage,
            'perPageSize'	=> 20
        );
        $request_arr = $this->Qsign($request_arr);
        $post = $this->Qpost($request_arr,$method);
        $post_arr=$this->unsetArray($post);
        $post_arr['totalCount']=$post['totalCount'];
        return $post_arr;
    }

    //单个产品获取
    public function singleProduct($productId){
        $method = '/openapi/singleProduct';

        $request_arr = array(
            'version'		=> '1.1.0',
            'partnerCode'	=> $this->partnerCode,
            'productId'		=> $productId
        );
        $request_arr = $this->Qsign($request_arr);
        $post_arr = $this->Qpost($request_arr,$method);
        return $post_arr;
    }
    public function unsetArray($post)
    {

        foreach($post['productInfos'] as $key =>$val){
            $post_arr['id']      = $post['productInfos'][$key]['productId'];
            $post_arr['sightId'] = $post['productInfos'][$key]['sightListItems'][0]['sightId'];
            $post_arr['Name']    = $post['productInfos'][$key]['productName'];
            $post_arrs['list'][] = $post_arr;
        }
        return $post_arrs;
    }

    //产品报价信息接口
    public function priceInfoList(){
        $method = '/openapi/priceInfoList';

        $request_arr = array(
            'version'		=> '1.0.0',
            'partnerCode'	=> $this->partnerCode,
            'pageNo'		=> 1,
            'perPageSize'	=> 100
        );
        $request_arr = $this->Qsign($request_arr);
        $post_arr = $this->Qpost($request_arr,$method);
        return $post_arr;
    }

    //单个报价信息接口
    public function singlePrice($productId){
        $method = '/openapi/singlePrice';

        $request_arr = array(
            'version'		=> '1.0.0',
            'partnerCode'	=> $this->partnerCode,
            'productId'		=> $productId
        );
        $request_arr = $this->Qsign($request_arr);
        $post_arr = $this->Qpost($request_arr,$method);
        return $post_arr;
    }

    //批量获取景点信息接口（可选）
    public function sightInfos(){
        $method = '/openapi/sightInfos';

        $request_arr = array(
            'version'		=> '1.0.0',
            'partnerCode'	=> $this->partnerCode,
            'pageNo'		=> 1,
            'perPageSize'	=> 100
        );
        $request_arr = $this->Qsign($request_arr);
        $post_arr = $this->Qpost($request_arr,$method);
        return $post_arr;
    }

    //根据景点Id获取景点信息（可选）
    public function getSightInfoBySightIds($sightIds){
        $method = '/openapi/getSightInfoBySightIds';

        $request_arr = array(
            'version'		=> '1.0.0',
            'partnerCode'	=> $this->partnerCode,
            'sightIds'		=> $sightIds
        );
        $request_arr = $this->Qsign($request_arr);
        $post_arr = $this->Qpost($request_arr,$method);
        return $post_arr;
    }

    //根据景点Id获取产品信息（可选）
    public function getProductInfoBySightIds($sightIds){
        $method = '/openapi/getProductInfoBySightIds';

        $request_arr = array(
            'version'		=> '1.1.0',
            'partnerCode'	=> $this->partnerCode,
            'sightIds'		=> $sightIds
        );
        $request_arr = $this->Qsign($request_arr);
        $post_arr = $this->Qpost($request_arr,$method);
        return $post_arr;
    }
    //计算签名
    public function Qsign($request_arr){
        ksort($request_arr);
        $o=""; 		 //不能用http_build_query的原因是这个函数会将中文转码
        foreach ($request_arr as $k=>$v){
            $o.= "$k=".$v."&";
        }
        $post_data=substr($o,0,-1);
        $arr = 'partnerKey='.$this->partnerKey.'&'.$post_data;
        $request_arr['sign'] = md5($arr);
        return $request_arr;
    }

    //请求接口服务的名称:门票景点详情
    public function TicketSenicSpotInfo($productid,$aid){
        $mes = $this->singleProduct($productid);

        $pri = $this->singlePrice($productid);
        $c   = count($pri['priceInfos']);
        $lid = $mes['productId'];
        $data= array();
        if($mes['limitEnterType']==0) {
            $use_delay_type=0;//0=不限制
            $advanceDay=0;
        }else if($mes['limitEnterType']==1 ||$mes['limitEnterType']==2 ) {
            if($mes['teamType']==0){
                $advanceDay="gsdf";
                $use_delay_type=2;//2=日历模式
            }else{
                $advanceDay=$mes['advanceDay'];
                $use_delay_type=1;//1=限制入园提前预订
            }
        }
        $mes['advanceTime']=empty($mes['advanceTime'])?'23:59:00':$mes['advanceTime'].":00";
        $data[$lid]['land']['detail']=$mes['useDescription']."</br>";
        foreach($mes['sightListItems'] as $mes_key =>$mes_val){
            $sightId   =  $mes_val['sightId'];
            $mess=$this->getSightInfoBySightIds($sightId);
            $lng_lat=explode(',',$mess[0]['googlePoint']);
            $data[$lid]['land']=array(
                'product_type'  =>  'A',
                'product_name'  =>  $mes['productName'],
                'city'          =>  $mess[0]['province'].'|'.$mess[0]['city'],
                'address'       =>  $mess[0]['address'],
                'product_level' =>  $mess[0]['score'],
                'tel'           =>  $mes['supplierTelPhone'],
                'fax'           =>  "",
                'opentime'      =>  $mess[0]['openTime'],
                'runtime'       =>  '',
                'imgpath'       =>  $mess[0]['sightImages'][0]['url'],
                'lat'           =>  $lng_lat[1],
                'lng'           =>  $lng_lat[0],//经度
                'notice'        =>  $mes['useDescription'],
                'aid'           =>  $aid
            );
            $data[$lid]['land']['detail'].=$mess[0]['introduction']."</br>";
            $data[$lid]['tickets'][]=array(
                'id'                =>$lid,
                'ticket_name'       =>$mess[0]['name'],
                'get_ticket_info'   =>$mes['useDescription'],
                'payment_type'      =>$mes['payWay']==0 ? 1 : 0,//1在线支付
                'total_storage'     =>$pri['priceInfos'][0]['availableCount']*$c,
                'auto_cancel_minute'=>120,
                'use_delay_type'    =>$use_delay_type,//当天有效   //0/1/2   0当天   1 游玩日期有效   2 手动设置日期
                'use_delay_days'    =>$advanceDay,    //当天有效
                'book_early_days'   =>0,    //资源提前预定天数
                'book_deadline'     =>$mes['advanceTime'],//提前预订截止时间
                'refundcharge'      =>$mes['refundPoundage'],//退票手续费
                'idcard_verify'     =>"",
                'buy_min_num'       =>$pri['priceInfos'][0]['minBuyCount'],
                'buy_max_num'       =>$pri['priceInfos'][0]['maxBuyCount'],
                'verify_start_time' =>'',
                'market_price'      =>$pri['priceInfos'][0]['marketPrice'],
                'update_time'       => date('Y-m-d H:i:s'),
                'Mpath'             =>'http://10.160.4.140/coop/To_Qunar/Qunar2B_get_data.php',//去哪儿的都是这个
                'sourceT'           =>2,//同上
                'price_array'       => array(
                    'start_date'        =>date('Y-m-d', $_SERVER['REQUEST_TIME']),
                    'end_date'          =>date('Y-12-30', $_SERVER['REQUEST_TIME']),
                    'valid_week'        => '0,1,2,3,4,5,6',
                    'storage'           =>$pri['priceInfos'][0]['availableCount'],
                    'supply_price'      =>$pri['priceInfos'][0]['qunarPrice']*100,
                    'retail_price'      =>$pri['priceInfos'][0]['marketPrice']*100,
                    'ptype'             =>0,
                ));
        }
        return($data);
    }

    //post提交
    public function Qpost($request_arr,$method){
        $Qurl=$this->Qurl.$method;
        $o="";
        foreach ($request_arr as $k=>$v){
            $o.= "$k=".$v."&";
        }
        $post_data=substr($o,0,-1);
        $this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL,$Qurl);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $reponse = curl_exec($ch);
        curl_close($ch);
        $response_data = json_decode($reponse,true);
        // print_r($response_data);exit;
        if($response_data['status']  == 1){
            $data = json_decode(base64_decode($response_data['data']),true);
            return $data;
        }
        return ($response_data['errorCode'].'|'.$response_data['errorMessage']);
    }

    public static function raw_post($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        return curl_exec($ch);
    }
}
$qunar2B = new Qunar2B();
// $productInfoList  = $qunar2B->productInfoList();
// $singleProduct  = $qunar2B->singleProduct('2484123458'); //测试产品id：3825423267
// $priceInfoList  = $qunar2B->priceInfoList();
// $singlePrice  = $qunar2B->singlePrice('2636733693');
// $sightInfos  = $qunar2B->sightInfos();
// $sightInfos  = $qunar2B->sightInfos();
// $getSightInfoBySightIds  = $qunar2B->getSightInfoBySightIds(10744);
// $getProductInfoBySightIds  = $qunar2B->getProductInfoBySightIds(10744);
?>